package com.sgb.kjwl.view.ui.adapter.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.util.Pair;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.util.List;

/**
 * Describe:    报价单位——货主视角适配器(普通货源)
 * Author:  yangLei
 * Date:    2021/9/23
 */
public class OfferOwnerAdapter4 extends BaseRecycleAdapter<OrderQuoteEntity> {

    private OnTabClickListener onTabClickListener;
    private Context context;

    public OfferOwnerAdapter4(Context context, List<OrderQuoteEntity> data) {
        super(context, R.layout.item_offer_owner_map_list, data);
        this.context = context;
    }

    public interface OnTabClickListener {
        void onAgreeClick(OrderQuoteEntity entity);

        void onChat(String account);

    }

    public void setOnTabClickListener(OnTabClickListener onTabClickListener) {
        this.onTabClickListener = onTabClickListener;
    }

    @Override
    public void convert(ItemViewHolder holder, OrderQuoteEntity entity) {
        TextView owner_name = holder.getItem().findViewById(R.id.owner_name);
        TextView freight_offer = holder.getItem().findViewById(R.id.freight_offer);
        TextView freight_offer_unit = holder.getItem().findViewById(R.id.freight_offer_unit);
        TextView car_hint = holder.getItem().findViewById(R.id.car_hint);
        ImageView car_iv = holder.getItem().findViewById(R.id.car_iv);
        TextView car_info = holder.getItem().findViewById(R.id.car_info);
        TextView position_info = holder.getItem().findViewById(R.id.position_info);
        TextView loading_distance = holder.getItem().findViewById(R.id.loading_distance);
        LinearLayout distance_bar = holder.getItem().findViewById(R.id.distance_bar);
        TextView offer_status = holder.getItem().findViewById(R.id.offer_status);
        TextView view_order = holder.getItem().findViewById(R.id.view_order);
        TextView agree_btn = holder.getItem().findViewById(R.id.right_btn);
        LinearLayout exchange_tab = holder.getItem().findViewById(R.id.exchange_tab);
        LinearLayout call_phone_tab = holder.getItem().findViewById(R.id.call_phone_tab);
        LinearLayout car_info_layout = holder.getItem().findViewById(R.id.car_info_layout);
        RelativeLayout handle_layout = holder.getItem().findViewById(R.id.handle_layout);
        View line_view = holder.getItem().findViewById(R.id.line_view);

        agree_btn.setText("下单");
        car_hint.setText("承运车辆");

        /*距离*/
        double distance = 0.0d;
        if (!TextUtils.isEmpty(entity.getDistance())) {
            distance = Double.parseDouble(entity.getDistance());
        } else if (entity.getLongitude() != null && entity.getLongitude() > 0
                && entity.getLatitude() != null && entity.getLatitude() > 0) {
            distance = LonLatUtils.getDistance(entity.getLongitude(), entity.getLatitude(),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, ""))
            );
        }
        if (distance <= 0) {
            loading_distance.setText("");
            distance_bar.setVisibility(View.GONE);
        } else {
            loading_distance.setText("距装货地 " + (distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km"));
            distance_bar.setVisibility(View.VISIBLE);
        }

        exchange_tab.setOnClickListener(v -> {
            if (isLogin()) {
                if (entity != null && !TextUtils.isEmpty(entity.getImAccount())) {
                    if (onTabClickListener != null) {
                        onTabClickListener.onChat(entity.getImAccount());
                    }
                }
            } else {
                VerificationCodeLoginActivity.start(context);
            }
        });
        call_phone_tab.setOnClickListener(v -> checkCanCall(entity));
        view_order.setOnClickListener(v -> skipOrder(entity));
        agree_btn.setOnClickListener(v -> showOfferDialog(entity));

        boolean bottomBarVisible = false;
        if (!TextUtils.isEmpty(entity.getOfferStatus())) {
            //1已报价  2待支付(已同意)  3已支付 4超时未支付 5已失效/货主未同意
            switch (entity.getOfferStatus()) {
                case "1":
                    agree_btn.setVisibility(View.VISIBLE);
                    view_order.setVisibility(View.GONE);
                    bottomBarVisible = true;
                    setBottomBarVisibility(handle_layout, line_view, true);
                    offer_status.setText("");
                    offer_status.setTextColor(Color.parseColor("#5792FD"));
                    break;

                case "2":
                    setBottomBarVisibility(handle_layout, line_view, false);
                    offer_status.setText("报价待支付");
                    offer_status.setTextColor(Color.parseColor("#FFC000"));
                    break;

                case "3":
                    agree_btn.setVisibility(View.GONE);
                    view_order.setVisibility(View.VISIBLE);
                    bottomBarVisible = true;
                    setBottomBarVisibility(handle_layout, line_view, true);
                    offer_status.setText("报价已支付");
                    offer_status.setTextColor(Color.parseColor("#06C764"));
                    break;

                case "4":
                case "5":
                    setBottomBarVisibility(handle_layout, line_view, false);
                    offer_status.setText("报价已失效");
                    offer_status.setTextColor(Color.parseColor("#C0C4CC"));
                    break;

                default:
                    offer_status.setText("");
                    setBottomBarVisibility(handle_layout, line_view, false);
                    break;
            }
        }
        if (!bottomBarVisible) {
            line_view.setVisibility(View.GONE);
            handle_layout.setVisibility(View.GONE);
        } else {
            line_view.setVisibility(View.VISIBLE);
            handle_layout.setVisibility(View.VISIBLE);
        }

        /*运费报价（单价）*/
        if (!TextUtils.isEmpty(entity.getFreight())) {
            freight_offer_unit.setText(NumberUtil.trim0(entity.getFreight()) + entity.getQuotationFreightUnit());
        }

        /*运费报价(总价)*/
        if (!TextUtils.isEmpty(entity.getAllFreight())) {
            freight_offer.setText(NumberUtil.trim0(entity.getAllFreight()) + "元");
        } else {
            freight_offer.setText("/");
        }

        //如果报价单位类型数据获取不到，则不处理该条数据
        if (TextUtils.isEmpty(entity.getOfferType())) {
            return;
        }
        String offerType = entity.getOfferType();
        offer_status.setVisibility(View.VISIBLE);
        String title = "";
        switch (offerType) {
            case "1"://企业
                car_info_layout.setVisibility(View.GONE);
                title = !TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "/";

                if (!TextUtils.isEmpty(entity.getFreightType())) {//先获取运费类型信息，为空无法处理
                    if (entity.getFreightType().equals("0")) {//一口价
                        if (entity.getIsVoluntarily() == 3) {//报价
                            if (entity.getPriceSection() != null) {
                                switch (entity.getPriceSection()) {
                                    case 1:
                                        car_iv.setImageResource(R.drawable.icon_quote_company_tint_red);
                                        break;
                                    case 2:
                                    default:
                                        car_iv.setImageResource(R.drawable.icon_quote_company_dark_red);
                                        break;
                                    case 3:
                                    case 5:
                                        car_iv.setImageResource(R.drawable.icon_quote_company_tint_green);
                                        break;
                                    case 4:
                                        car_iv.setImageResource(R.drawable.icon_quote_company_dark_green);
                                        break;
                                    case 6:
                                        car_iv.setImageResource(R.drawable.icon_quote_company_gray);
                                        break;
                                }
                            } else {//默认深红
                                car_iv.setImageResource(R.drawable.icon_quote_company_dark_red);
                            }
                        }
                    } else {//电议或者其他情况用深红色
                        car_iv.setImageResource(R.drawable.icon_quote_company_dark_red);
                    }
                }
                break;

            case "2"://团队
                car_info_layout.setVisibility(View.GONE);
                title = !TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "/";

                if (!TextUtils.isEmpty(entity.getFreightType())) {//先获取运费类型信息，为空无法处理
                    if (entity.getFreightType().equals("0")) {//一口价
                        if (entity.getIsVoluntarily() == 3) {//报价
                            if (entity.getPriceSection() != null) {
                                switch (entity.getPriceSection()) {
                                    case 1:
                                        car_iv.setImageResource(R.drawable.icon_quote_team_tint_red);
                                        break;
                                    case 2:
                                    default:
                                        car_iv.setImageResource(R.drawable.icon_quote_team_dark_red);
                                        break;
                                    case 3:
                                    case 5:
                                        car_iv.setImageResource(R.drawable.icon_quote_team_tint_green);
                                        break;
                                    case 4:
                                        car_iv.setImageResource(R.drawable.icon_quote_team_dark_green);
                                        break;
                                    case 6:
                                        car_iv.setImageResource(R.drawable.icon_quote_team_gray);
                                        break;
                                }
                            } else {//默认深红
                                car_iv.setImageResource(R.drawable.icon_quote_team_dark_red);
                            }
                        }
                    } else {//电议或者其他情况用深红色
                        car_iv.setImageResource(R.drawable.icon_quote_team_dark_red);
                    }
                }
                break;

            case "3"://个人
                if (entity.getDriverAuths() != null && entity.getDriverAuths().size() > 0 && entity.getDriverAuths().get(0) != null) {
                    OrderQuoteEntity.DriverAuth car = entity.getDriverAuths().get(0);
                    String carInfo = "";
                    if (!TextUtils.isEmpty(car.getCarTypeName()))
                        carInfo += car.getCarTypeName() + " ";
                    if (!TextUtils.isEmpty(car.getCarLenName()))
                        carInfo += "车长" + car.getCarLenName() + " ";
                    if (!TextUtils.isEmpty(car.getHeightHurdle()))
                        carInfo += "栏高" + NumberUtil.trim0(car.getHeightHurdle()) + "米 ";
                    car_info.setText(TextUtils.isEmpty(carInfo) ? "/" : carInfo);
                    car_info_layout.setVisibility(View.VISIBLE);

                    title = !TextUtils.isEmpty(car.getCarNumber()) ? car.getCarNumber() : "/";
                }
                if (!TextUtils.isEmpty(entity.getFreightType())) {//先获取运费类型信息，为空无法处理
                    if (entity.getFreightType().equals("0")) {//一口价
                        if (entity.getIsVoluntarily() == 3) {//报价
                            if (entity.getPriceSection() != null) {
                                switch (entity.getPriceSection()) {
                                    case 1:
                                        car_iv.setImageResource(R.drawable.icon_quote_car_tint_red);
                                        break;
                                    case 2:
                                    default:
                                        car_iv.setImageResource(R.drawable.icon_quote_car_dark_red);
                                        break;
                                    case 3:
                                    case 5:
                                        car_iv.setImageResource(R.drawable.icon_quote_car_tint_green);
                                        break;
                                    case 4:
                                        car_iv.setImageResource(R.drawable.icon_quote_car_dark_green);
                                        break;
                                    case 6:
                                        car_iv.setImageResource(R.drawable.icon_quote_car_gray);
                                        break;
                                }

                            } else {//默认深红
                                car_iv.setImageResource(R.drawable.icon_quote_car_dark_red);
                            }
                        }
                    } else {//电议或者其他情况用深红色
                        car_iv.setImageResource(R.drawable.icon_quote_car_dark_red);
                    }
                }
                break;
        }
        owner_name.setText(!TextUtils.isEmpty(title) ? title : "/");
        position_info.setText(!TextUtils.isEmpty(entity.getCompanyTeamAddress()) ? entity.getCompanyTeamAddress() : "/");
    }

    /**
     * 设置底部操作栏的显示隐藏
     *
     * @param handle_layout
     * @param line
     * @param visibility
     */
    private void setBottomBarVisibility(RelativeLayout handle_layout, View line, boolean visibility) {
        if (visibility) {
            handle_layout.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
        } else {
            handle_layout.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 拨号检查
     *
     * @param entity
     */
    private void checkCanCall(OrderQuoteEntity entity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(context);
            return;
        }
        if (!TextUtils.isEmpty(entity.getTelphone())) {
            showCallDialog(entity.getTelphone());
        } else {
            ToastUtil.show(context, "无联系方式");
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

    /**
     * 拨打电话对话框
     *
     * @param number
     */
    private void showCallDialog(String number) {
        new RoundDialog.Builder(context)
                .title("确认呼叫")
                .content(number)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> callPhone(number))
                .show();
    }

    /**
     * 展示同意报价对话框（普通货源）
     */
    private void showOfferDialog(OrderQuoteEntity entity) {
        String content;
        if (!TextUtils.isEmpty(entity.getSourceMessagePrice()) && !NumberUtil.trim0(entity.getSourceMessagePrice()).equals("0")) {//有信息费
            content = "下单后，承运人支付信息费后生成货运订单，您确定要下单吗？";
        } else {//无信息费
            content = "下单后，将生成货运订单，您确定要下单吗？";
        }
        new RoundDialog.Builder(context)
                .title("提示")
                .content(content)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    if (onTabClickListener != null)
                        onTabClickListener.onAgreeClick(entity);
                })
                .show();
    }

    /**
     * 跳转货运订单详情
     *
     * @param entity
     */
    private void skipOrder(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOrderNo())) {
            ActivityJump.jumpToActivity(context, TransportOrderDetailOwnerActivity.class, Pair.create("no", entity.getOrderNo()),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
        }
    }

    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }


    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */
    public static String replaceString2Star(String content, int frontNum, int endNum) {
        if (content == null || content.trim().isEmpty())
            return "";
        int len = content.length();

        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0)
            return content;

        if (frontNum + endNum >= len)
            return content;

        int beginIndex = frontNum;
        int endIndex = len - endNum;
        char[] cardChar = content.toCharArray();

        for (int j = beginIndex; j < endIndex; j++) {
            cardChar[j] = '*';
        }

        return new String(cardChar);
    }
}
